package com.fingard.dsp.bank.directbank.cbhb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

public class CBHB01Transaction extends CBHB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return d_7516_HisTrans(p_req7516, true);
    }

    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516, boolean p_isHisQuery) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;

            //按自然月循环查询

            //赋值通用参数
            CBHB01Header bankHeader = new CBHB01Header();
            bankHeader.TransCode = "QRACHS";
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int totalCount = 0;
                int queryCount = -1;
                while (queryCount < totalCount) {
                    bankHeader.ClientSeqno = getQryTransID();
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    xmlWriter.autoFormat = false;
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeStartElement("body");
                    xmlWriter.writeElementString("QueryType", p_isHisQuery ? "1" : "0");
                    xmlWriter.writeElementString("AcctNo", p_req7516.actNum);
                    xmlWriter.writeElementString("Ccy", convertCurToBank(p_req7516.actCur));
                    xmlWriter.writeElementString("BeginDate", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("EndDate", Format.Date10Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeEndDocument();

                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString().replace("<RecordIndex></RecordIndex>", String.format("<RecordIndex>%s</RecordIndex>", queryCount < 0 ? ++queryCount : queryCount)));
                    XmlTextReader tmpBkReader;
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpRetCode = tmpBkReader.getFirstText("/CBHB/head/RespondCode");
                            String tmpRetInfo = tmpBkReader.getFirstText("/CBHB/head/RespondInfo");
                            if (tmpRetCode != null && tmpRetCode.equals("000000")) {
                                if (totalCount <= 0) {
                                    totalCount = Integer.parseInt(String.valueOf(tmpBkReader.getFirstText("/CBHB/head/RecordTotal")));
                                }
                                String actNum = tmpBkReader.getFirstText("AcctNo");
                                while (tmpBkReader.read("/CBHB/body/TransList/Record")) {
                                    XElement tmpRecord = tmpBkReader.readedXElement;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actNum = actNum;
                                    String busDate = Format.Date8Format.format(Format.Date10Format.parse(tmpRecord.getSingleText("TranDate")));
                                    tmpRetDetail.urid = busDate + tmpRecord.getSingleText("SerSeqNo") + tmpRecord.getSingleText("AcctBal").replace(".", "");
                                    tmpRetDetail.tranDate = tmpRecord.getSingleText("TranDate");
                                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                    tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + "00:00:00";
                                    tmpRetDetail.usage = tmpRecord.getSingleText("Memo");
                                    tmpRetDetail.comment = tmpRecord.getSingleText("TranBrief");
                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage, tmpRetDetail.comment);
                                    tmpRetDetail.billType = tmpRecord.getSingleText("VouKind");
                                    tmpRetDetail.billNum = tmpRecord.getSingleText("VouNo");
                                    tmpRetDetail.cur = convertCurToATS(tmpRecord.getSingleText("TranCcy"));

                                    String tmpAMT = tmpRecord.getSingleText("TranAmt");
                                    String tmpFLAG1 = tmpRecord.getSingleText("CDFlag");
                                    tmpRetDetail.tranAmt = tmpAMT.replace("-", "");
                                    if (tmpFLAG1.equals("C")) {
                                        if (tmpAMT.indexOf("-") < 0) {

                                            tmpRetDetail.cdFlag = "2";
                                        } else {
                                            tmpRetDetail.cdFlag = "1";
                                        }
                                    } else if (tmpFLAG1.equals("D")) {
                                        if (tmpAMT.indexOf("-") < 0) {
                                            tmpRetDetail.cdFlag = "1";
                                        } else {
                                            tmpRetDetail.cdFlag = "2";
                                        }
                                    } else {
                                        throw new Exception("银行返回借贷标志（" + tmpFLAG1 + "）无法识别，请核对！");
                                    }

                                    tmpRetDetail.accBal = tmpRecord.getSingleText("AcctBal");
                                    tmpRetDetail.recAccName = tmpRecord.getSingleText("OppName");
                                    tmpRetDetail.recAccNum = tmpRecord.getSingleText("OppAcctNo");
                                    //返回付方开户行名
                                    if("2".equals(tmpRetDetail.cdFlag)) {
                                        tmpRetDetail.recAccBank = tmpRecord.getSingleText("TranBrcName");
                                    }
                                    queryCount++;
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else if ("999999".equals(tmpRetCode) && tmpRetInfo.contains("无明细")) {
                                tmpRespCode = "0";
                                tmpRespInfo = tmpRetInfo;
                                break;
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpRetInfo;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                }

                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516, false);
    }
}
